package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Logincheck.LoginCheck;
import com.example.entity.Login;
import com.example.mapper.LoginMapper;
import com.example.result.PageResult;
import com.example.result.Result;
import com.example.service.ILoginService;
import com.example.utils.JwtUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 陈昌吉
 * @since 2024-04-16
 */

@ResponseBody
@CrossOrigin
@Data
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILoginService  loginService;

    @Autowired
    public LoginMapper loginMapper;

    @GetMapping("/getAlllogin")
    public Result<List<Login>> getAlllogin(){
        return Result.success( loginService.getAll());
    }

    /**
     * 员工登录
     * @param login
     * @return
     */
    @Transactional
    @PostMapping("/login")
    public Result login(@RequestBody Login login){
     log.info("传过来得账号为:{}",login);
    Login login1=loginService.login(login);

       HashMap<String, Object> map = new HashMap<>();
       map.put("id",login1.getId());
       map.put("sno",login1.getSno());
       map.put("role",login1.getRole());
       String jwt = JwtUtil.createJWT(map);


       LoginCheck build = LoginCheck.builder()
               .id(login1.getId())
               .sno(login1.getSno())
               .role(login1.getRole())
               .token(jwt)
               .build();

       return Result.success(build);

    }

    //新增及修改
    @PostMapping("/addlogin")
    public Result<Login> addlogin(@RequestBody Login login){
        System.out.println(login.getId());
        if (login.getId()==0){
            loginService.addlogin(login);
        }else {
            loginMapper.updateById(login);
        }
        return Result.success();
    }

    //分页
    @PostMapping("/getLogin")
    public Result getLogin(@RequestBody Login login){
        PageResult logins =loginService.getLogin(login);
        System.out.println(logins);
        return Result.success(logins);
    }
    //删除
    @PostMapping("/deleteLogin")
    public Result deleteLogin(@RequestBody  Integer id){
        log.info("删除的id为{},",id);
        int i = loginMapper.deleteById(id);
        return Result.success(i);
    }
    //搜索
    @PostMapping("/searchLogin")
    public Result<List<Login>> searchLogin(@RequestBody Login login){
        log.info("查询的name为{}，",login.getName());
        List<Login> logins = loginService.searchLogin(login.getName());
        return Result.success(logins);
    }
}
